package com.mes.cloud.utils;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * 数字格式化
 * Created by Lenovo on 2017/2/23.
 */
public class NumberUtil {
    public static String numberFormat(double d, int i) {
        String num = null;
        if (i == 1) {
            num = "0.0";
        }
        if (i == 2) {
            num = "0.00";
        }
        if (i == 3) {
            num = "0.000";
        }
        if (i == 4) {
            num = "0.0000";
        }
        if (i == 0) {
            num = "0";
        }
        DecimalFormat nformat = new DecimalFormat(num);
        return nformat.format(d);
    }

    /***
     * @methodName percentToPoint
     * @date 2018/7/18 16:32
     * @param percent
     * @return java.lang.Double
     * 百分数转换成小数
     */
    public static Double percentToPoint(String percent){
        if(org.apache.commons.lang3.StringUtils.isEmpty(percent)){
            return -1.0;
        }
        if (!percent.matches("(100|[1-9]?\\d(\\.\\d\\d?\\d?)?)%$|0")) {
            return -1.0;
        }
        percent = percent.substring(0, percent.length() - 1);
        double parseDouble = Double.parseDouble(percent);
        return parseDouble/100;
    }

    /***
     * @methodName add
     * @date 2018/8/22 15:59
     * @param num1, num2
     * @return java.lang.Double
     * 两个数字相加，保留两位小数
     */
    public static Double add(Double num1, Double num2){
        BigDecimal bigDecimal1 = new BigDecimal(num1);
        BigDecimal bigDecimal2 = new BigDecimal(num2);
        BigDecimal bigDecimal = bigDecimal1.add(bigDecimal2);
        return bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
    }


    /***
     * @methodName add
     * @date 2018/8/22 15:59
     * @param num1, num2
     * @return java.lang.Double
     * 两个数字相加，保留两位小数
     */
    public static Double add(String num1, String num2){
        if(StringUtils.isEmpty(num1)){
            num1 = "0";
        }
        if(StringUtils.isEmpty(num2)){
            num2 = "0";
        }
        BigDecimal bigDecimal1 = new BigDecimal(num1);
        BigDecimal bigDecimal2 = new BigDecimal(num2);
        BigDecimal bigDecimal = bigDecimal1.add(bigDecimal2);
        return bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    /***
     * @methodName add
     * @date 2018/8/22 15:59
     * @param num1, num2
     * @return java.lang.Double
     * 两个数字相加，保留两位小数
     */
    public static Double modifyPoint(Double num1,int accuracy){
        BigDecimal bigDecimal = new BigDecimal(num1);
        return bigDecimal.setScale(accuracy,BigDecimal.ROUND_HALF_UP).doubleValue();
    }

}
